﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net.Mail;
using System.Security.Principal;
using System.Windows.Forms;

namespace SolidPrinciples.SingleResponsibility.Login
{
	/// <summary>
	/// SRP violation because does too much:
	/// 1. Analyses user input
	/// 2. Makes connection to database for login
	/// 3. Sends password reminders via SMTP
	/// </summary>
	public partial class LoginForm : Form
	{
		public LoginForm()
		{
			InitializeComponent();
		}

		private void remindPasswordButton_Click(object sender, EventArgs e)
		{
			if (emailTextBox.Text != string.Empty)
			{
				var mailMessage = new MailMessage();
				mailMessage.To.Add(emailTextBox.Text);
				mailMessage.Subject = "See your password";
				//...
				var client = new SmtpClient();
				client.Send(mailMessage);
			}
			
		}

		private void loginButton_Click(object sender, EventArgs e)
		{
			if (!string.IsNullOrWhiteSpace(emailTextBox.Text) && !string.IsNullOrWhiteSpace(passwordTextBox.Text))
			{
				var database = new ShopModelDataContext();
				var userLoggedIn = (from user in database.Users
				           where user.Email == emailTextBox.Text && user.Password == passwordTextBox.Text
				           select user).Single();

				System.Threading.Thread.CurrentPrincipal = userLoggedIn;

			}
			
		}
	}

	#region Helpers

	internal class ShopModelDataContext
	{
		public IEnumerable<User> Users
		{
			get { throw new NotImplementedException(); }
		}
	}

	internal class User : IPrincipal
	{
		public string Email { get; private set; }

		public string Password { get; private set; }

		public bool IsInRole(string role)
		{
			throw new NotImplementedException();
		}

		public IIdentity Identity { get; private set; }
	}

	#endregion
}
